from typing import Optional
from app.core.crud import CRUDBase
from app.models.admin import Menu
from app.schemas.menus import MenuCreate, MenuUpdate



class MenuController(CRUDBase[Menu, MenuCreate, MenuUpdate]):
    def __init__(self):
        super().__init__(model=Menu)

    async def get_by_menu_path(self, path: str) -> Optional["Menu"]:
        return await self.model.filter(path=path).first()

    async def get_menu_with_children(self, menu_id: int):
        menu = await menu_controller.model.get(id=menu_id)
        menu_dict = await menu.to_dict()
        child_menus = await menu_controller.model.filter(parent_id=menu_id).order_by("order")
        menu_dict["children"] = [await self.get_menu_with_children(child.id) for child in child_menus]
        return menu_dict

    async def get_menu_with_children2(self, menu_id: int):
        # 查询所有菜单，包括当前菜单和所有子菜单
        menus = await menu_controller.model.filter(is_hidden=0).order_by("order")

        # 将菜单列表转成字典，便于快速查找
        menu_dict = {menu.id: menu for menu in menus}

        # 构建菜单层级结构
        def build_menu_tree(parent_id: int):
            # 获取该父菜单下的子菜单
            children = [menu for menu in menus if menu.parent_id == parent_id]
            for child in children:
                # 递归构建子菜单的子菜单
                child_dict = build_menu_tree(child.id)
                child_dict["children"] = child_dict.get("children", [])
                menu_dict[child.id] = child_dict
            return {
                "id": menu_dict[parent_id].id,
                "name": menu_dict[parent_id].name,  # 假设有字段 'name'
                "path": menu_dict[parent_id].path,  # 假设有字段 'name'
                "icon": menu_dict[parent_id].icon,  # 假设有字段 'name'
                "children": [menu_dict[child.id] for child in children]
            }

        # 构建最终的菜单树
        return build_menu_tree(menu_id)


menu_controller = MenuController()
